package com.mh.mh.netty.protocal;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 客户端Handler
 * @author
 */
public class ProtocolClientHandlerMine extends ChannelInboundHandlerAdapter {

    /**
     * 客户端一旦与服务端建立好连接，就会触发该方法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送消息
        String data = "I am client ...";
        JSONObject json = new JSONObject();
        json.put("tip",data);

        // 获取要发送信息的字节数组
//        byte[] content = data.getBytes();
        byte[] content = json.toString().getBytes();
        // 要发送信息的长度
        int contentLength = content.length;

//        MyLsProtocol protocol = new MyLsProtocol(contentLength, content);
        MyLsProtocolMine protocol = new MyLsProtocolMine(contentLength, content);

        ctx.writeAndFlush(protocol);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // 用于获取客户端发来的数据信息
            MyLsProtocol body = (MyLsProtocol) msg;
            System.out.println("Client接收的服务端的信息：" + body.toString());
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
